﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Dashboard.ProductBonus.Business;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;

namespace Dashboard.ProductBonus
{
    public partial class FormAssistantTimeAdd : Form
    {
        public string TimeType { get; set; }
        public string ReasonCode { get; set; }
        public string ReasonName { get; set; }

        public FormAssistantTimeAdd()
        {
            InitializeComponent();
        }

        private void toolStripButtonCreate_Click(object sender, EventArgs e)
        {
            if (this.ultraGridMain.Rows.Count > 0)
            {
                if (MessageBox.Show(this, "Are you sure to re-create data?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            DateTime fromTime = this.dateTimePickerFrom.Value.Date;
            DateTime toTime = this.dateTimePickerTo.Value.Date;

            if (toTime < fromTime)
            {
                MessageBox.Show(this, "Date to can not earlier than Date from.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.dateTimePickerTo.Focus();
                return;
            }

            DataTable result = GetEmptyDataSource();

            while (fromTime <= toTime)
            {
                result.Rows.Add(new object[] { fromTime, null, null, 0 });
                fromTime = fromTime.AddDays(1);
            }

            result.AcceptChanges();

            this.ultraGridMain.DataSource = result;
        }

        private DataTable GetEmptyDataSource()
        {
            DataTable result = new DataTable();
            result.Columns.Add("Date", typeof(DateTime));
            result.Columns.Add("FromTime", typeof(DateTime));
            result.Columns.Add("ToTime", typeof(DateTime));
            result.Columns.Add("TotalTime", typeof(Int32));
            result.AcceptChanges();

            return result;
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.ultraGridMain.UpdateData();
                if (this.ultraGridMain.Rows.Count == 0)
                {
                    MessageBox.Show(this, "No data found, please assign and entry the time.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (this.comboBoxStaffNo.SelectedItem == null)
                {
                    MessageBox.Show(this, "Please choose a valid staff.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.comboBoxStaffNo.Focus();
                    return;
                }

                List<string> sqlList = new List<string>();
                UnproductiveTime at = new UnproductiveTime();

                UltraGridRow row;
                string staffNo = this.comboBoxStaffNo.Text.Split('-')[0];

                for (int i = 0; i < this.ultraGridMain.Rows.Count; i++)
                {
                    row = this.ultraGridMain.Rows[i];

                    // 检查是否已经存在当天的记录
                    if (at.ExistUnproductiveTime(staffNo, (DateTime)row.Cells["Date"].Value, this.ReasonCode))
                    {
                        MessageBox.Show(this, string.Format("There is already an " + this.ReasonName + " record of the date [{0}].", ((DateTime)row.Cells["Date"].Value).ToString("yyyy-MM-dd")), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        row.Selected = true;
                        return;
                    }

                    if (string.IsNullOrEmpty(Convert.ToString(row.Cells["TotalTime"].Value)))
                    {
                        MessageBox.Show(this, "Total Time can not be empty.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        row.Selected = true;
                        return;
                    }
                    if (int.Parse(row.Cells["TotalTime"].Value.ToString()) == 0)
                    {
                        MessageBox.Show(this, "Total Time can not be zero.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        row.Selected = true;
                        return;
                    }

                    /*
                    if (string.IsNullOrEmpty(Convert.ToString(row.Cells["FromTime"].Value)))
                    {
                        MessageBox.Show(this, "From Time can not be empty.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        row.Selected = true;
                        return;
                    }

                    if (string.IsNullOrEmpty(Convert.ToString(row.Cells["ToTime"].Value)))
                    {
                        MessageBox.Show(this, "To Time can not be empty.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        row.Selected = true;
                        return;
                    }
                    */

                    string fromTime = string.IsNullOrEmpty(Convert.ToString(row.Cells["FromTime"].Value)) ? "null" : "'" + ((DateTime)row.Cells["FromTime"].Value).ToString("HH:mm") + "'";
                    string toTime = string.IsNullOrEmpty(Convert.ToString(row.Cells["ToTime"].Value)) ? "null" : "'" + ((DateTime)row.Cells["ToTime"].Value).ToString("HH:mm") + "'";

                    sqlList.Add("INSERT INTO abnormalworkingtime (staffno,timetype,reasoncode,date,fromtime,totime,totaltime,insertby,insertdate,updatedby,updateddate) " +
                        " VALUES('" + staffNo + "', '" + this.TimeType + "','" + this.ReasonCode + "','" + ((DateTime)row.Cells["Date"].Value).ToString("yyyy-MM-dd") + "'," +
                        " " + fromTime + "," + toTime + "," +
                        " " + (int)row.Cells["TotalTime"].Value + ",'" + CommonBusiness.GetCurrentLoginUser() + "',getdate(),'" + CommonBusiness.GetCurrentLoginUser() + "',getdate()) ");
                }

                at.AddNewUnproductiveTimes(sqlList);

                MessageBox.Show(this, "Save successfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void ultraGridMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;

            // 滚动提示
            e.Layout.Bands[0].ScrollTipField = "StaffNo";

            // 隐藏不需要显示的列
            e.Layout.Bands[0].Columns["Date"].CellActivation = Infragistics.Win.UltraWinGrid.Activation.NoEdit;
            e.Layout.Bands[0].Columns["FromTime"].CellClickAction = CellClickAction.EditAndSelectText;
            e.Layout.Bands[0].Columns["ToTime"].CellClickAction = CellClickAction.EditAndSelectText;
            e.Layout.Bands[0].Columns["TotalTime"].CellClickAction = CellClickAction.EditAndSelectText;

            //e.Layout.Bands[0].Columns["FromTime"].Header.Appearance.ForeColor = Color.Red;
            //e.Layout.Bands[0].Columns["ToTime"].Header.Appearance.ForeColor = Color.Red;
            e.Layout.Bands[0].Columns["TotalTime"].Header.Appearance.ForeColor = Color.Red;

        }

        private void ultraGridMain_AfterCellUpdate(object sender, Infragistics.Win.UltraWinGrid.CellEventArgs e)
        {
            this.ultraGridMain.UpdateData();
            if (e.Cell.Column.Key == "FromTime" || e.Cell.Column.Key == "TotalTime")
            {
                // 按照FromTime和TotalTime计算ToTime，FromTime和ToTime只是参考而已
                if (string.IsNullOrEmpty(Convert.ToString(e.Cell.Row.Cells["TotalTime"].Value))
                    || string.IsNullOrEmpty(Convert.ToString(e.Cell.Row.Cells["FromTime"].Value)))
                {
                    return;
                }

                int totalTime = int.Parse(Convert.ToString(e.Cell.Row.Cells["TotalTime"].Value));
                DateTime fromTime = (DateTime)e.Cell.Row.Cells["FromTime"].Value;
                DateTime toTime = fromTime.AddHours(totalTime);

                e.Cell.Row.Cells["ToTime"].Value = toTime;
            }
            this.ultraGridMain.UpdateData();
        }

        private void FormAssistantTimeAdd_Load(object sender, EventArgs e)
        {
            this.Text = "Add " + this.TimeType + "Time";
            this.toolStripLabelTitle.Text = this.Text;
            this.BindTeamList();
            this.BindStaffNoList();
        }

        private void BindTeamList()
        {
            BusinessBase bb = new BusinessBase();
            DataTable teams = bb.LoadTeamList();

            this.comboBoxTeam.Items.Clear();

            foreach (DataRow row in teams.Rows)
            {
                this.comboBoxTeam.Items.Add(row["team"].ToString());
            }

            if (this.comboBoxTeam.Items.Count > 0)
            {
                this.comboBoxTeam.SelectedIndex = 0;
            }

            bb = null;
        }

        private void BindStaffNoList()
        {
            BusinessBase bb = new BusinessBase();
            DataTable staffs = bb.GetStaffOfTeam(this.comboBoxTeam.Text);

            this.comboBoxStaffNo.Items.Clear();
            this.comboBoxStaffNo.Text = string.Empty;

            foreach (DataRow row in staffs.Rows)
            {
                if (row["WorkType"].ToString().IndexOf("班长") >= 0 || row["WorkType"].ToString().IndexOf("辅助") >= 0)
                {
                    continue;
                }
                this.comboBoxStaffNo.Items.Add(row["staffno"].ToString() + "-" + row["name"].ToString());
            }
            if (this.comboBoxStaffNo.Items.Count > 0)
            {
                this.comboBoxStaffNo.SelectedIndex = 0;
            }
            bb = null;
        }

        private void comboBoxTeam_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindStaffNoList();
        }
    }
}
